package com.gushenge.core

import android.content.Context
import android.os.Build
import android.telephony.TelephonyManager
import android.util.Base64
import android.util.Log
import android.widget.Toast
import com.gushenge.atools.util.ADate
import com.gushenge.core.base.Base.BASEURL
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.dao.RetrofitDao
import com.hjq.toast.ToastUtils
import com.readystatesoftware.chuck.ChuckInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.lang.reflect.ParameterizedType
import java.net.Proxy
import java.net.ProxySelector
import java.net.SocketAddress
import java.net.URI
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
import java.util.concurrent.TimeUnit
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import kotlin.math.log

val isShangjia = MMKVConsts.shangjia == "1"


val client = OkHttpClient.Builder()
//     .proxySelector(object : ProxySelector(){
//         override fun select(uri: URI?): MutableList<Proxy> {
//             Log.e("TAG", "selectaaaaaaaaa: "+uri?.authority  +"--"+uri?.path )
//             return Collections.singletonList(Proxy.NO_PROXY)
//         }
//
//         override fun connectFailed(uri: URI?, sa: SocketAddress?, ioe: IOException?) {
//         }
//
//     })
    .addInterceptor(HeadInterceptor())
    .addInterceptor(CustomLogInterceptor())
//        .addInterceptor(ChuckInterceptor(CoreApplication.instance))
    .connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).build()

fun HttpQuery(): RetrofitDao {
    val retrofit = Retrofit.Builder().baseUrl(BASEURL).client(client).addConverterFactory(
        GsonConverterFactory.create()
    ).build()
    return retrofit.create(RetrofitDao::class.java)
}

fun getIMEI(context: Context, slotId: Int): String {
    return try {
        val manager: TelephonyManager =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val method =
            manager.javaClass.getMethod("getImei", Int::class.javaPrimitiveType)
        method.invoke(manager, slotId).toString()
    } catch (e: java.lang.Exception) {
        ""
    }
}
/*AES加密*/

// 加密
@Throws(Exception::class)
fun aesEcb(sSrc: String): String {
    val sKey = "mtetbpryjhdxmnhx"
    val raw = sKey.toByteArray(charset("utf-8"))
    val skeySpec = SecretKeySpec(raw, "AES")
    val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")//"算法/模式/补码方式"
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
    val encrypted = cipher.doFinal(sSrc.toByteArray(charset("utf-8")))
    val aesCrypt = Base64.encodeToString(encrypted, Base64.DEFAULT)//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    return aesCrypt.replace("+", "_")
}

// 加密
@Throws(Exception::class)
fun aesEcbDecode(sSrc: String): String {
    val string = sSrc.replace("_", "+")
    val decode = Base64.decode(string, Base64.DEFAULT)
    val sKey = "mtetbpryjhdxmnhx"
    val raw = sKey.toByteArray(charset("utf-8"))
    val skeySpec = SecretKeySpec(raw, "AES")
    val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")//"算法/模式/补码方式"
    cipher.init(Cipher.DECRYPT_MODE, skeySpec)
    return cipher.doFinal(decode).toString(charset("utf-8"))

}

var timeStamp = ""

val time: String
    get() {
        timeStamp = ADate.getStampAs13().toString()
        return timeStamp
    }

/*接口验证*/
fun httpSign(vararg string: String): String {

    var result = ""
    for (key in string) {
        result += key
    }
    result += timeStamp
    result += "fsd213ewdsadqwe2121213edsad"
    return md5(result)
}

@Suppress("UNCHECKED_CAST")
fun <VM> getVmClazz(obj: Any): VM {
    return (obj.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as VM
}

fun Any?.toast() {
    if (this.toString().isNotBlank()) {
        ToastUtils.show(this.toString())
    }
}

/*MD5加密*/
fun md5(string: String): String {
    try {
        //获取md5加密对象
        val instance: MessageDigest = MessageDigest.getInstance("MD5")
        //对字符串加密，返回字节数组
        val digest: ByteArray = instance.digest(string.toByteArray())
        val sb: StringBuffer = StringBuffer()
        for (b in digest) {
            //获取低八位有效值
            val i: Int = b.toInt() and 0xff
            //将整数转化为16进制
            var hexString = Integer.toHexString(i)
            if (hexString.length < 2) {
                //如果是一位的话，补0
                hexString = "0" + hexString
            }
            sb.append(hexString)
        }
        return sb.toString()

    } catch (e: NoSuchAlgorithmException) {
        e.printStackTrace()
    }

    return ""
}
